import { observable, action } from 'mobx';
import { Tools, Toast, Bubble } from 'weaver-mobile';
import { ListViewPage } from 'weaver-mobile-page';
import { Base64 } from "js-base64";
import _ from "lodash";
import { toJS } from 'mobx';

const { getFrameParams } = Tools;
const getLabel = Tools.getLabel;

function loop() { }
const LANG = {
  PREFIX: "~`~`",
  SPLITTER: "`~`",
  SUFFIX: "`~`~"
};

export default class HomePageTestStore {
  @observable passed = false;
  @observable menuConfig = [];
  @observable hidenMenuConfig = [];
  @observable initMenuConfig = [];
  @observable activeKey = [];
  @observable showGroup = true;
  @observable disableMenu = false;
  @observable wfCount = 0;
  @observable showIntro = false;
  @observable isEdit = false;
  @observable isInit = false;
  @observable initEntrancePage = true;
  @observable hasCustom = false;
  @observable hasAdd = false;
  @observable hasIntro = false;

  @observable list = new ListViewPage.Store({ route: '/messageList' });
  @observable tabData = [];
  @observable tabFlag = '0';
  @observable bizstate = '';
  @observable tabSelectedKey = '';
  @observable listParams = {};
  @observable selectedTab = 'Message';
  @observable listRef = {};
  @observable refreshing = false;
  @observable hasNoMore = false;
  @observable loading = false;
  @observable needScroll = true;
  @observable oldScrollHeight = 0;
  @observable isMenuInited = false;
  @observable isHidenmenuInited = false;
  @observable needRefresh = false;
  @observable scrollInTop = false;
  @observable showCountList = [];
  @observable showCountListInfo = {};
  @observable isInitMessagePage = true;
  @observable messagePageIndex = 0;
  @observable bannerFlag = '';
  @observable bannerImg = '';
  @observable bannerHeight = '';
  @observable app_datas = [];
  @observable pageId = '';
  @observable appPage = {};
  @observable appPageHiden = {};
  @observable groupDelids = [];

  // pullToRefresh need render one more time to get ref
  @observable timer = null;
  @observable hasRenderOneMoreTime = false;

  @observable username = '';
  @observable password = '';
  // @observable currentItem = '';

  @observable roundUrl = '';

  @action
  setPass = (pass) => {
    this.passed = pass;
  }

  @action
  setListRef = (ref) => {
    this.listRef = ref;
  }

  @action
  setNeedScroll = (needScroll) => {
    this.needScroll = needScroll;
  }

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  }

  @action
  onChange = (key) => {
    this.activeKey = key;
  }

  doSort = (arr, key, order = 1) => arr.sort((a, b) => {
    if (parseInt(a[key]) < parseInt(b[key])) {
      return -order;
    } else if (parseInt(a[key]) > parseInt(b[key])) {
      return order;
    }
    return 0;
  });

  getCurrentLabel = (multiStr, langId) => {
    const localeLanguageId = langId || window.localStorage.getItem('languageidweaver') || '7';
    const list = {};
    if (typeof multiStr === "string" && multiStr.indexOf(LANG.PREFIX) > -1) {
      multiStr = multiStr.substring(4);
      multiStr = multiStr.substring(0, multiStr.length - 4);
      multiStr.split(LANG.SPLITTER).map((item) => {
        list[item.substr(0, 2).replace(" ", "")] = item.substr(2);
      });
      return list[localeLanguageId] || multiStr;
    } else {
      return multiStr;
    }
  }

  @action
  getMenuConfig = (cb = loop) => {
    if (this.hasAdd) {
      this.isMenuInited = false;
    }

    if (this.showGroup === true) {
      this.hasIntro = false
    }
    const urlParams = getFrameParams();
    const id = urlParams['id'] || '';
    let url = '/api/system/appPage/appEntrancePage/getPageById?id=' + id;
    if (urlParams['checkAccess'] === '1') {
      url = '/api/system/appPage/appEntrancePage/accessAppList?pageid=' + id;
    }
    return Tools.callApi({
      url: url,
      method: 'GET'
    }).then((result) => {
      let groupDatas = result.group_datas;
      let appDatas = result.app_datas;
      let appPage = result.appPage;
      this.app_datas = result.app_datas;
      this.appPage = result.appPage;
      this.isInit = result.isInit;
      if (result.group_delids) {
        Object.keys(result.group_delids).forEach((key) => {
          this.groupDelids.push(result.group_delids[key]);
        })
      }
      if (!result.app_datas) {
        alert('获取菜单信息失败，请尝试退出应用重新进入工作台');
        return;
      }
      if (appPage && appPage.showgroup === '0') {
        this.showGroup = false;
      }
      if (appPage && appPage.status === 'n') {
        this.disableMenu = true;
      }
      if (appPage && appPage.bannerFlag) {
        this.bannerFlag = appPage.bannerFlag;
      }
      if (appPage && appPage.id) {
        this.pageId = appPage.id;
        this.appPage = appPage;
      }
      if (appPage && appPage.bannerImg) {
        this.bannerImg = appPage.bannerImg;
      }
      if (appPage && appPage.bannerHeight) {
        this.bannerHeight = appPage.bannerHeight;
      }
      if (appPage && appPage.title) {
        if (appPage.title.indexOf("base64_") > -1) {
          appPage.title = this.getCurrentLabel(Base64.decode(appPage.title.substr(7)));
        }
        document.title = appPage.title;
      }

      this.doSort(groupDatas, 'show_order');
      this.doSort(appDatas, 'module_show_order');

      // if (appDatas.length < 1){
      //   this.isEdit = true;
      // }

      let groupArr = {};
      for (let index = 0; index < groupDatas.length; index++) {
        const group = groupDatas[index];
        if (group.name.indexOf("base64_") > -1) {
          group.name = this.getCurrentLabel(Base64.decode(group.name.substr(7)));
        }
        groupArr[group.id + 'group'] = {
          groupTitle: group.name,
          groupItem: []
        };
      }

      let groupMenuConfig = [];

      for (let index = 0; index < appDatas.length; index++) {
        const app = appDatas[index];
        app.hiden = false;
        if (app.showcount === 'y' && app.apptype === '1') {
          this.showCountList.push(app.appid);
        }
        try {
          const groupItemTemp = [...groupArr[app.module_group + 'group'].groupItem];
          if (app.module_visible.indexOf("base64_") > -1) {
            app.module_visible = this.getCurrentLabel(Base64.decode(app.module_visible.substr(7)));
          }

          let appItem = {
            id: app.id,
            itemTitle: app.module_visible,
            itemIcon: app.img_src,
            itemUrl: app.homeurl,
            itemCusIcon: app.cus_imgurl,
            itemType: app.apptype,
            showCount: app.showcount === 'y' ? true : false,
            showCountType: app.showCountType,
            appid: app.appid,
            androidScheme: app.androidScheme,
            androidUrl: app.androidUrl,
            iosScheme: app.iosScheme,
            iosUrl: app.iosUrl,
            openApp: app.openApp,
            module_group: app.module_group,
            module_show_order: app.module_show_order,
            updateTime: app.updateTime,
            hiden: app.hiden,
            inteSwitch: app.inteSwitch,
            inteSysid: app.inteSysid,
            openType: app.openType,
          }

          if (this.showGroup || this.isEdit) {
            groupItemTemp.push(appItem);
            groupArr[app.module_group + 'group'].groupItem = groupItemTemp;
          } else {
            if (groupMenuConfig.length < 1) {
              groupItemTemp.push(appItem);
            } else {
              let unique = true;
              groupMenuConfig.map((item, index) => {
                if (item.id === appItem.id) {
                  unique = false
                }
              })
              unique && groupItemTemp.push(appItem);
            }
            groupMenuConfig = groupMenuConfig.concat(groupItemTemp)
          }
        } catch (error) {
          alert('菜单分组数据异常');
        }
      }

      this.initMenuConfig = _.cloneDeep(appDatas)

      if (this.showGroup || this.isEdit) {
        const menuData = [];
        for (const key in groupArr) {
          if (groupArr.hasOwnProperty(key) && groupArr[key].groupItem.length) {
            const element = groupArr[key];

            // 去重
            let foundObject = _.find(this.menuConfig, function (e) {
              return e.groupTitle === element.groupTitle;
            });

            if (foundObject) {
              this.menuConfig.map((item, index) => {
                if (item.groupTitle === element.groupTitle) {
                  this.menuConfig.splice(index, 1)
                }
              })
            }

            if (this.isEdit && !this.showGroup) {
              menuData.push(element)
            } else {
              this.menuConfig.push(element)
            }
          }
        }

        if (this.isEdit && !this.showGroup) {
          this.menuConfig = menuData;
        }
      } else {
        groupMenuConfig = _.groupBy(groupMenuConfig, 'module_group')

        groupDatas.map((item, index) => {
          for (const key in groupMenuConfig) {
            if (groupMenuConfig.hasOwnProperty(key) && groupMenuConfig[key].length) {
              if (item.id === key) {
                const element = groupMenuConfig[key];
                this.menuConfig = this.menuConfig.concat(element)
              }
            }
          }
        })
      }

      let length = [];
      for (let index = 0; index < this.menuConfig.length; index++) {
        length.push(index + '');
      }
      this.activeKey = length;
      cb();
    }).catch((err) => {

    }).finally(() => {
      this.isMenuInited = true;
    });
  }

  @action
  getMessageData = (params, needRefresh, needScroll = true, cb = loop) => {
    needRefresh && (this.refreshing = true);
    needRefresh && (this.needRefresh = true);
    !needRefresh && (this.loading = true);
    !needRefresh && (this.needRefresh = false);

    params.bizstate = this.bizstate;

    const urlParams = getFrameParams();
    if (urlParams['typeId']) {
      params.typeId = urlParams['typeId'];
    }
    try {
      Tools.callApi({
        method: 'POST',
        url: '/api/msgcenter/homepage/getMsgList',
        params,
      }).then(action((res) => {
        if (this.isInitMessagePage && res.data && res.data.length === 0) {
          if (this.tabFlag === "1") {
            let allKeyArr = [];
            let allIndexArr = [];

            this.tabData.forEach((item, index) => {
              if (!item.msgStateId) {
                allKeyArr.push(item.viewcondition);
                allIndexArr.push(index);
              }
            })

            this.bizstate = allKeyArr.length ? '' : this.tabData[0].msgStateId;
            this.tabSelectedKey = allKeyArr[0] || this.tabData[0].viewcondition;
            this.messagePageIndex = allIndexArr[0] || 0;
            this.getMessageData(params, true, needScroll, cb)
          };
        }

        const data = res.data
        const newState = {
          loading: false,
          current: params.current || 1,
          data: [...res.data, ...(params.current === 1 ? [] : this.list.data)],
          rowKey: 'messageid',
          isTable: false,
          template: { default: [] },
          typeId: res.typeId,
          mintime: res.mintime,
          msgid: res.msgid,
        };

        if (res.data.length > 0) {
          this.oldScrollHeight = res.data.length * 190;
        }

        this.hasNoMore = (data.length < 10);
        this.hasRenderOneMoreTime = (data.length < 10);
        this.loading = false;
        this.list.setState(newState);
        this.list.updateDataSource();
        this.renderOneMoreTime();
        this.isInitMessagePage = false;
        needRefresh && (this.refreshing = false);
        needScroll && (this.needScroll = true);
        cb();
      }))
    } catch (e) {
      cb();
      Toast.info(e, 1);
    }
  }

  // pullToRefresh need render one more time to get ref
  @action
  renderOneMoreTime = () => {
    if (!this.hasRenderOneMoreTime) {
      this.timer = setTimeout(() => {
        this.list.updateDataSource();
        if (this.timer) {
          clearTimeout(this.timer);
          this.timer = null;
          this.hasRenderOneMoreTime = true;
        }
      }, 100);
    }
  }

  @action
  updateScroll(oldScrollHeight, needRefresh) {
    const doms = document.getElementsByClassName('wm-list-view-page-modal-scrollview')
    if (doms.length > 0) {
      if (needRefresh) {
        doms[0].scrollTop = doms[0].scrollHeight
      } else {
        doms[0].scrollTop = doms[0].scrollHeight - oldScrollHeight;
      }
    }
  }

  @action
  getWfCount = () => {
    let params = {
      ismobile: 1,
      menuids: this.showCountList.join(','),
    }

    Tools.callApi({
      method: 'POST',
      url: '/api/workflow/emAppCount/doingCount',
      params,
    }).then(action((res) => {
      this.showCountListInfo = { ...this.showCountListInfo, ...res };
    }));

    for (let index = 0; index < this.app_datas.length; index++) {
      const app = this.app_datas[index];
      if (app.countUrl) {
        params = {
          moduleid: app.appid,
        }
        Tools.callApi({
          method: 'GET',
          url: app.countUrl,
          params,
        }).then(action((res) => {
          this.showCountListInfo = { ...this.showCountListInfo, [app.appid]: res };
        }));
      }
    }
  }

  @action
  getCorner = () => {
    let params = {
      pageId: this.pageId
    }
    return Tools.callApi({
      method: 'POST',
      url: '/api/system/appmanage/corner',
      params,
    }).then(action((res) => {
      this.isMenuInited = true;
      if (res.datas) {
        res.datas.map(item => {
          this.showCountListInfo = { ...this.showCountListInfo, [Object.keys(item)[0]]: { unread: Object.values(item)[0] } };
        })
      }
      if (res.roundurl) {
        this.roundUrl = res.roundurl
      }
    })).finally(() => {
      this.isMenuInited = true;
    });

    for (let index = 0; index < this.app_datas.length; index++) {
      const app = this.app_datas[index];
      if (app.countUrl) {
        params = {
          moduleid: app.appid,
        }
        Tools.callApi({
          method: 'GET',
          url: app.countUrl,
          params,
        }).then(action((res) => {
          this.showCountListInfo = { ...this.showCountListInfo, [app.appid]: res };
        }));
      }
    }

  }


  @action
  getCount = () => {
    if (!this.roundUrl) {
      return;
    }
    Tools.callApi({
      method: 'GET',
      url: this.roundUrl,
    }).then(action((res) => {
      if (res.datas) {
        res.datas.map(item => {
          this.showCountListInfo = { ...this.showCountListInfo, [Object.keys(item)[0]]: { unread: Object.values(item)[0] } };
        })
      }
    }));
  }

  @action
  getMsgTypeTabs = () => {
    const urlParams = getFrameParams();

    return Tools.callApi({
      method: "GET",
      url: "/api/msgcenter/homepage/GetMsgTypeTabs",
      params: {
        typeId: urlParams['typeId'] ? urlParams['typeId'] : ''
      }
    }).then((res) => {
      if (res.datas && res.datas.length) {
        let datas = JSON.parse(
          JSON.stringify(res.datas)
            .replace(/id/g, "viewcondition")
            .replace(/tabName/g, "title")
        );
        this.tabData = datas;
        this.tabFlag = '1';
        this.tabSelectedKey = datas[0].viewcondition;
        this.bizstate = datas[0].msgStateId;
      }
    })
  }

  @action
  saveMenuConfig = (id) => {
    if (!this.hasCustom) {
      this.isEdit = false;
      this.isMenuInited = true;
      if (!this.showGroup) {
        this.isMenuInited = false;
        this.getMenuConfig(() => {
          this.getCorner()
        })
      }
      return false;
    }

    if (!id) {
      this.isMenuInited = false;
    }
    let allAppDatas = [];
    let hiddenAppItem = {};
    const updateTime = new Date().toLocaleDateString().replace(/\//g, "-") + " " + new Date().toTimeString().substr(0, 8) + ":" + new Date().getMilliseconds();

    this.menuConfig.map((item) => {
      allAppDatas = allAppDatas.concat(toJS(item.groupItem));
    })

    for (let i = 0, lenI = this.initMenuConfig.length; i < lenI; i++) {
      if (id) {
        if (this.initMenuConfig[i].id === id) {
          this.initMenuConfig[i].updateTime = updateTime;
          this.initMenuConfig[i].hiden = true;
          hiddenAppItem = this.initMenuConfig[i];
        }
      } else {
        for (let j = 0, lenJ = allAppDatas.length; j < lenJ; j++) {
          if (allAppDatas[j].id === this.initMenuConfig[i].id) {
            this.initMenuConfig[i].module_show_order = allAppDatas[j].module_show_order;
          }
        }
      }
    }

    return Tools.callApi({
      method: 'POST',
      url: '/api/system/appUser/appUserSetting/hidenSort',
      params: {
        appPage: JSON.stringify(this.appPage),
        app: id ? JSON.stringify([hiddenAppItem]) : JSON.stringify(this.initMenuConfig),
        group_delids: [],
        app_delids: [],
      },
    }).then((res) => {
      if (res.status) {
        if (!id) {
          this.isEdit = false;
          this.getMenuConfig().then(() => {
            this.getCorner();
          })
        }
      }
    })
  }

  @action
  resetMenuConfig = () => {
    this.hasCustom = true;
    this.isMenuInited = false;
    return Tools.callApi({
      method: 'POST',
      url: '/api/system/appUser/appUserSetting/hidenSort',
      params: {
        identification: 'defaultSort',
        appPage: JSON.stringify(this.appPage)
      },
    }).then((res) => {
      if (res.status) {
        this.getMenuConfig().then(() => {
          this.getCorner();
        })
      }
    }).finally(() => {
      this.isMenuInited = true;
    })
  }

  updateRead = () => {
    const urlParams = getFrameParams();
    Tools.callApi({
      method: 'GET',
      url: '/api/msgcenter/homepage/setMsgRead',
      params: {
        id: urlParams.typeId
      },
    })
  }

  @action
  getHidenMenuConfig = (cb = loop) => {
    const urlParams = getFrameParams();
    this.appPageHiden.id = urlParams['id'];

    return Tools.callApi({
      url: '/api/system/appUser/appUserSetting/setHidenAppDisplay',
      method: 'POST',
      params: {
        appPage: JSON.stringify(this.appPageHiden),
        group_delids: [],
        app_delids: []
      },
    }).then((result) => {
      this.hidenMenuConfig = [];
      let groupDatas = result.group_datas;
      let appDatas = result.app_datas;
      let appPage = result.appPage;
      this.app_datas = result.app_datas;
      if (!result.app_datas) {
        return;
      }

      if (appPage && appPage.status === 'n') {
        this.disableMenu = true;
      }
      if (appPage && appPage.id) {
        this.pageId = appPage.id;
      }
      if (appPage && appPage.title) {
        if (appPage.title.indexOf("base64_") > -1) {
          appPage.title = this.getCurrentLabel(Base64.decode(appPage.title.substr(7)));
        }
        document.title = appPage.title;
      }

      for (let index = 0; index < appDatas.length; index++) {
        const app = appDatas[index];
        try {
          if (app.module_visible.indexOf("base64_") > -1) {
            app.module_visible = this.getCurrentLabel(Base64.decode(app.module_visible.substr(7)));
          }
          const itemTemp = [];
          itemTemp.push(app);
          this.hidenMenuConfig.push(itemTemp);
        } catch (error) {
          alert('数据异常');
        }
      }
      this.isHidenmenuInited = true;
      cb();
    }).catch((err) => {
      cb();
      console.log(err);
    });
  }

  @action
  addhidenItem = (item) => {
    const itemId = item.id;
    this.hidenMenuConfig.forEach((app, index) => {
      let appObj = Object.assign(...app);
      if (appObj.id === itemId) {
        this.hasAdd = true;
        this.hidenMenuConfig.splice(index, 1);
      }
    })
    this.removeHidenApp(item);
  }

  @action
  removeHidenApp = (item) => {
    this.item = item;
    this.item.hiden = false;
    Tools.callApi({
      method: 'POST',
      url: '/api/system/appUser/appUserSetting/setHidenAppDisplay',
      params: {
        appPage: JSON.stringify(this.appPageHiden),
        app: JSON.stringify([item]),
        group_delids: [],
        app_delids: []
      },
    })
  }

  // @action
  // getOutterPCAndAppUrl = (item) => {
  //   // item.itemUrl = item.itemUrl.replace('&hasEmCode=1', '').replace('?hasEmCode=1', '');
  //   Tools.callApi({
  //     method: 'POST',
  //     url: '/api/integration/OutterPCAndApp/getOutterPCAndAppUrl',
  //     params: {
  //       sysid: item.inteSysid,
  //     },
  //   }).then((result) => {
  //     if (result.appUrl && result.appUrl.indexOf('/integration/accountSetting') !== -1) {
  //       // 跳到账号登陆页面
  //       // this.username = result.userName;
  //       // this.password = result.passWord;
  //       // history.push('/single-sign');
  //       // 跳转到集成用户录入页面，需要传递inteSwitch 和 homeUrl参数给集成页面
  //       // 如果inteSwitch==1,集成直接跳转集成地址；否则，需要跳转homeUrl并拼接用户录入参数
  //       const newUrl = '/spa/integration/static4mobile/index.html#/accountSetting?inteSwitch=' + item.inteSwitch + '&openType=' + item.openType + '&inteSysid=' + item.inteSysid + '&homeUrl=' + encodeURIComponent(item.itemUrl);
  //       if (window.em && window.localStorage.emobile_ec_id) {
  //         window.em.checkJsApi("openLink") && window.em.openLink({
  //           url: newUrl,
  //           openType: 2,
  //           sysId: window.localStorage.emobile_ec_id,
  //           error: function (error) {
  //             alert(JSON.stringify(error));
  //           }
  //         })
  //         !window.em.checkJsApi("openLink") && window.openLink(newUrl);
  //       } else {
  //         window.openLink(newUrl);
  //       }
  //     } else {
  //       // 不需要用户录入
  //       if (item.inteSwitch === '1') {
  //         // 集成地址,直接跳转
  //         if (window.em) {
  //           let params = {};
  //           let appScheme = result.appUrl;
  //           if (result.appUrl.indexOf('?') !== -1) {
  //             let urlParams = getFrameParams(result.appUrl);
  //             let keys = Object.keys(urlParams);
  //             let values = Object.values(urlParams);
  //             keys.map((item, index) => {
  //               params[item] = values[index];
  //             })
  //             appScheme = appScheme.split('?')[0];
  //           }
  //           window.em.checkJsApi("openApp") && window.em.openApp({
  //             iOSscheme: appScheme,
  //             androidscheme: appScheme,
  //             params: params,
  //             error: function (error) {
  //               alert(JSON.stringify(error));
  //             }
  //           })
  //           !window.em.checkJsApi("openApp") && window.openLink(result.appUrl);
  //         } else {
  //           window.openLink(result.appUrl);
  //         }
  //       } else {
  //         // 拼接集成参数
  //         let param = '';
  //         if (result.appUrl && result.appUrl.indexOf('?') !== -1) {
  //           param = result.appUrl.slice(result.appUrl.indexOf('?') + 1);
  //         }
  //         let url = item.itemUrl;
  //         let split = '';
  //         if (/.*\?.*/.test(item.itemUrl)) {
  //           split = '&'
  //           if (/.*\?.*#\/(?!.*\?).*/.test(item.itemUrl)) {
  //             split = '?'
  //           }
  //         } else {
  //           split = '?'
  //         }
  //         if (param) {
  //           url += split + param;
  //         }
  //         // result && Object.keys(result).map(key => {
  //         //   url = url + '&' + key + '=' + result[key];
  //         // })
  //         if (window.em) {
  //           window.em.checkJsApi("openLink") && window.em.openLink({
  //             url: url,
  //             openType: item.openType || 2,
  //             error: function (error) {
  //               alert(JSON.stringify(error));
  //             }
  //           })
  //           !window.em.checkJsApi("openLink") && window.openLink(url);
  //         } else {
  //           window.openLink(url);
  //         }
  //       }
  //     }
  //   })
  // }

  // @action
  // insertAccount = (history) => {
  //   if (!this.username) {
  //     Bubble.error('请输入账号')
  //   } else if (!this.password) {
  //     Bubble.error('请输入密码')
  //   } else {
  //     Tools.callApi({
  //       method: 'POST',
  //       url: '/api/integration/OutterPCAndApp/insertAccount',
  //       params: {
  //         sysid: this.currentItem.inteSysid,
  //         ['userName_' + this.currentItem.inteSysid]: this.username,
  //         ['passWord_' + this.currentItem.inteSysid]: this.password,
  //       },
  //     }).then((result) => {
  //       if (window.em) {
  //         window.em.checkJsApi("openApp") && window.em.openApp({
  //           iOSscheme: result.appUrl,
  //           androidscheme: result.appUrl,
  //           error: function (error) {
  //             alert(JSON.stringify(error));
  //           }
  //         })
  //         !window.em.checkJsApi("openApp") && window.openLink(result.appUrl);
  //       } else {
  //         window.openLink(result.appUrl);
  //       }
  //       history.go(-1)
  //     })
  //   }
  // }
}
